package com.xxr.mom.ci.charging.message.mq;

import com.xxr.mom.ci.charging.interworking.data.SynchronizeDeviceData;
import com.xxr.mom.ci.charging.interworking.dto.InterworkingConfigDto;
import com.xxr.mom.ci.charging.interworking.dto.RePushDto;
import com.xxr.mom.ci.charging.message.MessageChannel;
import com.xxr.mom.ci.common.log.LogTrace;
import com.xxr.mom.ci.common.util.Constant;
import com.xxr.mom.ci.common.util.JsonUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.ThreadContext;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @description: MqMessageChannel
 * @date: 2024/8/22 22:10
 * @author: natsuki_kining
 * @version: 1.0
 */
@Log4j2
@Component
public class RocketMQMessageChannel implements MessageChannel {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public boolean sendDeviceInfoMessage(SynchronizeDeviceData synchronizeDeviceData) {
        log.info("发送推送站点MQ消息：{}", synchronizeDeviceData);
        SendResult sendResult = rocketMQTemplate.syncSend(Constant.MqTopic.SYNCHRONIZE_DEVICE_TOPIC, synchronizeDeviceData, TIMEOUT);
        log.info("发送推送站点MQ消息结果：{}", sendResult);
        return sendResult.getSendStatus() == SendStatus.SEND_OK;
    }

    /**
     * 重新推送
     *
     * @param data
     * @return
     */
    public void rePush(Object data, InterworkingConfigDto configDto, int delay) {
        RePushDto rePushDto = new RePushDto(ThreadContext.get(LogTrace.TRACE_ID), data, configDto);
        Message<RePushDto> message = MessageBuilder.withPayload(rePushDto).build();
        rocketMQTemplate.asyncSend(Constant.MqTopic.RE_PUSH, message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("重新推送MQ发送成功：{}", JsonUtil.toJSONString(sendResult));
            }

            @Override
            public void onException(Throwable e) {
                log.info("重新推送MQ发送失败：{}", e.getMessage(), e);
            }
        }, TIMEOUT, delay);
    }

    public void sendLog(Object data, InterworkingConfigDto configDto) {

    }
}
